package com.wyj.databinding

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.ViewModel
import com.wyj.controller.UIController
import com.wyj.utils.asActivity
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable

open class BaseViewModel : ViewModel(), LifecycleObserver, UIController.IActivityLauncher {
    lateinit var activityLauncher: UIController.IActivityLauncher
    val uiChangeLiveData = UIChangeLiveData()

    //管理RxJava，主要针对RxJava异步操作造成的内存泄漏
    private val mDisposables = CompositeDisposable()

    class UIChangeLiveData : IUIChangeEvent {
        override val loadingDialogEvent = SingleLiveEvent<Boolean>()
        override val finishEvent = SingleLiveEvent<Unit>()
        override val binding = SingleLiveEvent<ViewDataBinding>()
        val screenOrientation = SingleLiveEvent(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        fun <T : ViewDataBinding> getBinding(): T? = binding.value as? T
        fun getContext(): Context? = binding.value?.root?.context
        fun <T : Activity> getActivity(): T? = getContext()?.asActivity<T>()
    }


    override fun getCurrentContext(): Context? {
        return activityLauncher.getCurrentContext()
    }

    override fun launch(intent: Intent, callback: ((resultCode: Int, data: Intent?) -> Unit)?) {
        activityLauncher.launch(intent, callback)
    }

    protected open fun addDisposable(disposable: Disposable?) {
        if (disposable != null) {
            mDisposables.add(disposable)
        }
    }

    override fun onCleared() {
        super.onCleared()
        mDisposables.dispose()
    }
}